import hashlib
import hmac
import datetime
import time


# str_obj 将目标对象转为字符串
def str_obj(obj: str):
    str_result = ""
    if type(obj) == str:
        str_result = obj
    elif type(obj) == int:
        str_result = str(obj)
    elif type(obj) is datetime.datetime:
        str_result = obj.strftime('%Y-%m-%d %H:%M:%S')
    elif type(obj) is datetime.time:
        str_result = obj.strftime('%H:%M:%S')
    elif obj is None:
        str_result = ""
    return str_result


# quoted_str 将目标字符串加上
def quoted_str(str: str):
    str_result = "'"
    for ch in str:
        if ch == "'":
            str_result += "''"
        else:
            str_result += ch
    str_result += "'"
    return str_result


# get_now_stamp13 毫秒级时间戳
def get_now_stamp13():
    # 生成13时间戳   eg:1557842280000
    # datetime_str = datetime.datetime.strftime(datetime_obj, '%Y-%m-%d %H:%M:00')
    # datetime_obj = datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:00')
    # print(datetime_obj)
    datetime_obj = datetime.datetime.now()
    # 10位，时间点相当于从1.1开始的当年时间编号
    date_stamp = str(int(time.mktime(datetime_obj.timetuple())))
    # 3位，微秒
    data_microsecond = str("%06d" % datetime_obj.microsecond)[0:3]
    date_stamp = date_stamp + data_microsecond
    return int(date_stamp)


# get_now_stamp13 秒级时间戳
def get_now_stamp10():
    import datetime, time
    datetime_obj = datetime.datetime.now()
    print(datetime_obj)
    # 10位，时间点相当于从1.1开始的当年时间编号
    date_stamp = str(int(time.mktime(datetime_obj.timetuple())))
    return int(date_stamp)


# gen_token_content token需要加密的内容
def gen_token_content(appkey, appsecret, nonce, timestamp13):
    content = f"appkey={appkey}&appsecret={appsecret}&nonce={nonce}&timestamp={timestamp13}"
    return content


# hmac_sha256 sha256加密
def hmac_sha256(data: str, secret: str):
    bytes_secret = secret.encode('utf-8')  # 秘钥
    bytes_content = data.encode('utf-8')  # 加密数据
    result = hmac.new(bytes_secret, bytes_content, digestmod=hashlib.sha256).hexdigest()
    return result


# gen_token_sign 组合拿到sign
def gen_token_sign(appkey, appsecret, nonce, timestamp13):
    content = gen_token_content(appkey, appsecret, nonce, timestamp13)
    # print("token content is ", content)
    return hmac_sha256(content, appsecret)


# gen_ticket_sign 组合拿到ticket的sign
def gen_ticket_sign(appsecret, nonce, ticket, timestamp13):
    content = f"appsecret={appsecret}&nonce={nonce}&ticket={ticket}&timestamp={timestamp13}"
    print("token content is ", content)
    return hmac_sha256(content, appsecret)


# json_default_headers 缺省header的值
def json_default_headers():
    return {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Accept-Encoding": "identity",
        "User-Agent": "python-urllib3/2.1.0"
    }

